package com.ews.onlineexchange.service;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.Image;

@Model
public class ImageThumbnailService {
	
	@Inject
	EntityManager entityManager;
	
	@Transactional
	public String generate() {
		Session session = (Session) entityManager.getDelegate();
		session.setCacheMode(CacheMode.IGNORE);
		session.setFlushMode(FlushMode.MANUAL);
		Query query = session.createQuery("SELECT i FROM Image i");
		ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
		long count = 0L;
		
		while (sr.next()) {
			Image image = (Image) sr.get()[0];
			image.setFiledata(image.getFiledata());
			entityManager.merge(image);
			
			count++;
			if (count % 10 == 0) {
				session.flush();
				session.clear();
			}
		}		
		session.flush();
		return "ok";
	}
}
